package cn.tiga.system.service.impl;

import cn.tiga.system.domain.Menu;
import cn.tiga.system.mapper.MenuMapper;
import cn.tiga.system.service.IMenuService;
import cn.tiga.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pping
 * @since 2022-08-02
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {
        List<Menu> allMenus = menuMapper.loadAll();

        //避免双重for循环
        Map<Long, Menu> map = new HashMap<>();
        //将所有部门装到map中
        for (Menu menu : allMenus) {
            map.put(menu.getId(), menu);
        }

        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu : allMenus) {
            //如果是顶级部门 - 就添加到部门数
            if (menu.getParentId() == null) {
                menuTree.add(menu);
            } else {//有父级部门
                Menu menu1 = map.get(menu.getParentId());
                if (menu1 != null) {
                    menu1.getChildren().add(menu1);
                }
            }
        }
        return menuTree;
    }
}
